<template>
  <div class="register">
    <div class="register-container">
      <div class="register-content">
        <div class="register-header">
          <h2>HIS医院信息系统</h2>
          <p class="subtitle">用户注册</p>
        </div>
        <el-card class="register-card" shadow="never">
          <el-form
            ref="registerFormRef"
            :model="formData"
            :rules="rules"
            @submit.prevent="handleRegister"
          >
            <el-form-item prop="username">
              <el-input 
                v-model="formData.username" 
                placeholder="请输入用户名"
                :prefix-icon="User"
                size="large"
              />
            </el-form-item>
            <el-form-item prop="email">
              <el-input 
                v-model="formData.email" 
                placeholder="请输入邮箱"
                :prefix-icon="Message"
                size="large"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="formData.password" 
                type="password" 
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
                size="large"
              />
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input 
                v-model="formData.confirmPassword" 
                type="password" 
                placeholder="请确认密码"
                :prefix-icon="Lock"
                show-password
                size="large"
              />
            </el-form-item>
            <el-form-item prop="first_name">
              <el-input
                v-model="formData.first_name"
                :prefix-icon="User"
                placeholder="请输入姓名"
                size="large"
              />
            </el-form-item>
            <el-form-item prop="role">
              <el-select
                v-model="formData.role"
                placeholder="请选择角色"
                size="large"
                style="width: 100%"
              >
                <el-option label="医生" value="doctor" />
                <el-option label="护士" value="nurse" />
                <el-option label="管理员" value="admin" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button 
                type="primary" 
                native-type="submit"
                :loading="loading"
                class="register-button"
                size="large"
              >
                注册
              </el-button>
            </el-form-item>
            <div class="login-link">
              已有账号？
              <el-button 
                type="text" 
                @click="handleLogin"
                class="login-button"
              >
                立即登录
              </el-button>
            </div>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()

// 注册表单数据
const formData = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  first_name: '',
  role: ''
})

// 验证密码是否一致
const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== formData.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  first_name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 表单引用
const registerFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 处理登录跳转
const handleLogin = () => {
  router.push('/login')
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    // 表单验证
    await registerFormRef.value.validate()
    
    loading.value = true
    
    // 先获取CSRF令牌
    const csrfResponse = await fetch('/api/auth/csrf/', {
      credentials: 'include'
    })
    if (!csrfResponse.ok) {
      throw new Error('获取CSRF令牌失败')
    }
    const { csrfToken } = await csrfResponse.json()

    // 发送注册请求
    const response = await fetch('/api/auth/register/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': csrfToken
      },
      credentials: 'include',
      body: JSON.stringify({
        username: formData.username,
        email: formData.email,
        password: formData.password,
        first_name: formData.first_name,
        role: formData.role
      })
    })
    
    if (!response.ok) {
      throw new Error('注册失败')
    }

    const data = await response.json()
    if (data.status === 'success') {
      ElMessage.success('注册成功，请登录')
      router.push('/login')
    } else {
      throw new Error(data.message || '注册失败')
    }
  } catch (error: any) {
    console.error('注册错误:', error)
    ElMessage.error(error.message || '注册失败，请检查输入')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register {
  min-height: 100vh;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.register-container {
  width: 100%;
  max-width: 400px;
}

.register-content {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  padding: 30px;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.register-card {
  border: none;
  background: transparent;
  box-shadow: none !important;
}

.register-card :deep(.el-card__body) {
  padding: 0;
}

.register-button {
  width: 100%;
}

.login-link {
  text-align: center;
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
}

.login-button {
  padding: 0 5px;
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}
</style> 